import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Router, NavigationStart} from "@angular/router";

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
	menuUrlList:any = [];
	whiteList:any = []
	constructor(private router: Router) {
		this.router.events.filter((event:any) => event instanceof NavigationStart).subscribe((event:any) => {
		    this.menuUrlList = [];
            if (localStorage.getItem('s-menu-url')) {
                this.menuUrlList = JSON.parse(decodeURIComponent(localStorage.getItem('s-menu-url')));//权限菜单
                let whiteList:any = ['/auth','/system/blank','/auth/error404'];//白名单,这些页面不做权限限制
                this.menuUrlList = whiteList.concat(this.menuUrlList)
            }
		    let URL = event.url.split('?')[0].split('/'),testUrl,testUrl2;
		    if (!URL[2]) {
		    	testUrl = event.url;
		    } else {
		    	testUrl = '/'+URL[1]+'/'+URL[2];
		    	if(URL[3]){
		    		testUrl2 = '/'+URL[1]+'/'+URL[2]+'/'+URL[3];
		    	}
		    }
		    if(this.menuUrlList.length > 0){
		    	if (this.menuUrlList.indexOf(testUrl2) < 0 && this.menuUrlList.indexOf(testUrl) < 0) {
			    	this.router.navigate(['/auth/error404']);
			    }
		    }
	  	})
	}
	canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
		const { link, path } = route.data
		if (this.isLingANdHttpUrl({link: link, path: path})) {
			this.openNewWindow(path)
			return false
		}
		// 返回值 true: 跳转到当前路由 false: 不跳转到当前路由
		const isLogin = common.getCookie('isLogin');
		if (!isLogin) {// 未登录，跳转到login
			this.router.navigate(['/auth']);
			return false;
		} else {// 已登录，跳转到当前路由
			return true;
		}
	}
	canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
		const { link, path } = childRoute.data
		if (this.isLingANdHttpUrl({link: link, path: path})) {
			this.openNewWindow(path)
			return false
		}
		const viewerContainers: any = window.document.querySelectorAll('.viewer-container')
		const datetimepicker: any = window.document.querySelectorAll('.datetimepicker')
		for (const item of viewerContainers) {
			item.parentNode.removeChild(item)
		}
		for (const item of datetimepicker) {
			item.parentNode.removeChild(item)
		}
		return true
	}

	/*
	* @des: 校验跳转的路由path是否是链接并且是否是完整http/https链接
	* @param: link:(string) 是否是链接 ===Link/true
	* @param: path:(string) 跳转的路由path
	* @return: (boolean)
	* */
	isLingANdHttpUrl({link, path}) {
		const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
		return link === 'Link' && reg.test(path)
	}

	/*
	* @des: 跳转到帮助中心
	* @param: url:(string) 跳转链接
	* @return: (null)
	* */
	openNewWindow(url) {
		const urlTemp = `${url}?token=${localStorage.getItem('token')}`
		window.open(urlTemp)
	}

}